package chapter04.udf;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Description(
        name = "zodiac",
        value = "_FUNC_(date) - from the input date string " +
                ", returns the sign of the Zodiac.",
        extended = "Example: \n" +
                "> SELECT _FUNC_(date_string) FROM src;\n"
)
public class ZodiacUDF extends UDF {
    private SimpleDateFormat dateFormat;

    public ZodiacUDF() {
        dateFormat = new SimpleDateFormat("MM-dd-yyyy");
    }

    public String evaluate(String birthDay) {
        Calendar calendar = Calendar.getInstance();
        Date date = null;

        try {
            date = dateFormat.parse(birthDay);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int month = calendar.get(Calendar.MONTH) + 1;  // from 0 to ...
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        return evaluate(month, day);
    }

    private String evaluate(int month, int day) {
        //
        String zodiac = null;
        switch (month) {
            case 1:
                zodiac = day < 20 ? "摩羯座" : "水瓶座";
                break;
            case 2:
                zodiac = day < 19 ? "水瓶座" : "双鱼座";
                break;
            case 3:
                zodiac = day < 21 ? "双鱼座" : "白羊座";
                break;
            case 4:
                zodiac = day < 20 ? "白羊座" : "金牛座";
                break;
            case 5:
                zodiac = day < 21 ? "金牛座" : "双子座";
                break;
            case 6:
                zodiac = day < 22 ? "双子座" : "巨蟹座";
                break;
            case 7:
                zodiac = day < 23 ? "巨蟹座" : "狮子座";
                break;
            case 8:
                zodiac = day < 23 ? "狮子座" : "处女座";
                break;
            case 9:
                zodiac = day < 23 ? "处女座" : "天秤座";
                break;
            case 10:
                zodiac = day < 24 ? "天秤座" : "天蝎座";
                break;
            case 11:
                zodiac = day < 23 ? "天蝎座" : "射手座";
                break;
            case 12:
                zodiac = day < 22 ? "射手座" : "摩羯座";
                break;
            default:;
        }

        return zodiac;
    }
}
